<template>
  <div class="create-post-page">
    <h4 >{{isEditMode ? '更新文章': '新建文章'}}</h4>
    <Uploader action="/upload" :uploaded="uploadedData" @file-uploaded="handleFileUploaded" class="d-flex align-items-center justify-content-center bg-light text-secondary width-100 my-4" :beforeUpload="beforeUpload">
    <h2>点击上传头像</h2>
     <template #loading>
        <div class="d-flex justify-content-center">
          <div class="spinner-border text-secondary" role="status">
          </div>
          <h2>正在上传</h2>
        </div>
     </template>

     <template #successload="dataprops">
    <img :src="dataprops.uploadedData.data.url">
  </template>

    </Uploader>  <!-- 这里的标签传递到了默认插槽里 -->
  <validate-form @form-submit="onFormSubmit">
     <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
     </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows='10'
          type="text"
          tag="textarea"
          placeholder="请输入文章详情"
         :rules="contentRules"
          v-model="contentVal"
        />
      </div>
<template #submit>
<button class="btn btn-primary shadow">{{isEditMode ? '更新文章': '新建文章'}}</button>
</template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '../store'
import ValidateInput, { EmailRules } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import Uploader from '@/components/Uploader.vue'
import createMessage from '../createMessage'
export default defineComponent({
  name: 'CreatPost',
  components: {
    ValidateInput,
    ValidateForm,
    Uploader
  },
  setup () {
    const uploadedData = ref()
    const route = useRoute()
    const isEditMode = !!route.query.id// 这里是来判断这个是否是编辑模式下的创建文章
    const titleVal = ref('')
    const router = useRouter()
    const store = useStore<GlobalDataProps>()
    const titleRules: EmailRules[] = [
      { type: 'required', message: '文章标题不能为空' }
    ]

    const contentVal = ref('')
    const contentRules: EmailRules[] = [
      { type: 'required', message: '文章详情不能为空' }]

    const beforeUpload = (file: File) => {
      const isjpg = file.type === 'image/jpeg'
      if (!isjpg) {
        createMessage('上传文件只能是JPG格式', 'error')
      }
      return isjpg
    }
    onMounted(() => {
      if (isEditMode) {
        console.log(isEditMode, 565)

        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          console.log(route.query.id)
          console.log(rawData)
          /// 这里是一个undefined，但是id号

          const currentPost = rawData.data
          console.log(currentPost)

          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title || ''
          contentVal.value = currentPost.content || ''
        }
        )// 这里就是编辑的时候想把当前 的内容初始化到这个创建文章的界面上。
      }
    })

    let imageId = ''
    const handleFileUploaded = (rawdata: ResponseType<ImageProps>) => {
      if (rawdata.data._id) {
        imageId = rawdata.data._id
      }
    }// 这里就是子组件定义事件，然后父组件接受这个事件并去执行，并返沪这个成功的结果，更具后端接口可以找到发送的图片的id号
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user// 这里要拿到这个对应的用户id号

        if (column) {
          const newpost: PostProps = {
          // _id: 'new Date().getTime()',
            title: titleVal.value,
            content: contentVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id
          }
          if (imageId) {
            newpost.image = imageId
          } // 这里逻辑
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newpost
          } : newpost

          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功，2秒后跳转至文章首页', 'success', 2000)
            setTimeout(() => {
              router.push({ name: 'Column', params: { id: column } })
            }, 2000)
          })// 这里的逻辑
        }
      }
    }
    return {
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      beforeUpload,
      handleFileUploaded,
      uploadedData,
      isEditMode
    }
  }
})
</script>
